<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="success" icon="el-icon-plus" style="margin-right: 20px"
        @click="handleCreate">
        新增
      </el-button>
      航点名称：<el-input v-model="listQuery.wayPointName" placeholder="航点名称" style="width: 200px; margin-right: 20px"
        class="filter-item" @keyup.enter.native="handleFilter" />
      状态：<el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 200px; margin-right: 20px"
        class="filter-item">
        <el-option label="启用" value="1" />
        <el-option label="停用" value="0" />
      </el-select>

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px" type="info" icon="el-icon-refresh-right"
        @click="handleRefresh">
        重置
      </el-button>
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column label="序号" prop="id" width="100">
        <template slot-scope="{ row, $index }">
          {{ (listQuery.pageNo - 1) * listQuery.pageSize + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="航点编号" prop="wayPointNo" />
      <el-table-column label="航点名称" prop="wayPointName" />
      <el-table-column label="航点经度" prop="wayPointLongitude" />
      <el-table-column label="航点纬度" prop="wayPointLatitude" />
      <el-table-column label="飞行高度" prop="flightHeight" />
      <el-table-column label="创建时间" prop="createTime" width="180" />
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row }">
          <el-tag v-if="row.status == 1" type="success" size="small">启用</el-tag>
          <el-tag v-else type="info" size="small">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{ row, $index }">
          <el-button v-if="row.status == 0" size="mini" type="success" @click="handleStatus(row)">
            启用
          </el-button>
          <el-button v-if="row.status == 1" size="mini" type="danger" @click="handleStatus(row)">
            停用
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px"
        style="width: 100%; margin-left: 10px;padding-right: 20px;">
        <el-form-item label="航点编号" prop="wayPointNo">
          <el-input v-model="temp.wayPointNo" placeholder="请输入航点编号" />
        </el-form-item>
        <el-form-item label="航点名称" prop="wayPointName">
          <el-input v-model="temp.wayPointName" placeholder="请输入航点名称" />
        </el-form-item>
        <el-form-item label="航点经纬度" prop="wayPointLongitude">
          <div id="qyContainer" element-loading-text="数据更新中" element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(25,81,135,0.7)" />
        </el-form-item>
        <el-form-item label="航点经度" prop="wayPointLongitude">
          <el-input v-model="temp.wayPointLongitude" placeholder="请选择航点经度" :disabled="true" />
        </el-form-item>
        <el-form-item label="航点纬度" prop="wayPointLatitude">
          <el-input v-model="temp.wayPointLatitude" placeholder="请选择航点纬度" :disabled="true" />
        </el-form-item>
        <el-form-item label="飞行高度" prop="flightHeight">
          <el-input v-model="temp.flightHeight" type="number" placeholder="请输入飞行高度" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" :loading="btnLoading"
          @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  waypointList,
  waypointAdd,
  waypointDel,
  waypointUpdate,
  waypointStatus
} from '@/api/uavairline'
import { formatDate } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import AMapLoader from '@amap/amap-jsapi-loader'
export default {
  name: 'Airpoint',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      btnLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        wayPointName: undefined,
        status: undefined
      },
      temp: {
        id: undefined,
        wayPointNo: '',
        wayPointName: '',
        wayPointLongitude: '',
        wayPointLatitude: '',
        flightHeight: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        wayPointNo: [
          { required: true, message: '请输入航点编号', trigger: 'change' }
        ],
        wayPointName: [
          { required: true, message: '请输入航点名称', trigger: 'change' }
        ],
        wayPointLongitude: [
          { required: true, message: '请选择航点经度', trigger: 'change' }
        ],
        wayPointLatitude: [
          { required: true, message: '请选择航点纬度', trigger: 'change' }
        ],
        flightHeight: [
          { required: true, message: '请输入飞行高度', trigger: 'change' }
        ]
      },
      center: [126.578085, 43.859222],
      AMap: null,
      markers: [
        {
          name: '',
          lat: '',
          lng: ''
        }
      ],
      marker: []
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    window._AMapSecurityConfig = {
      securityJsCode: 'e5c0fe8d40233deb748b07cfa09ab739'
    }
  },
  methods: {
    init(row = null) {
      this.$nextTick(() => {
        AMapLoader.load({
          key: '3bccb9b5337ca1ae0bd58577c6f1ed14',
          version: '2.0',
          plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.LngLat', 'AMap.Marker'],
          AMapUI: {
            version: '1.1',
            plugins: ['overlay/SimpleMarker']
          }
        })
          .then((AMap) => {
            this.AMap = AMap
            this.map = new AMap.Map('qyContainer', {
              viewMode: '2D',
              zoom: 14,
              // mapStyle: 'amap://styles/darkblue', // 地图样式，可以自定义
              center: row
                ? [row.wayPointLongitude, row.wayPointLatitude]
                : this.center
            })

            // 添加toolbar--放大缩小
            const toolbar = new AMap.ToolBar()
            this.map.addControl(toolbar)
            this.map.on('click', this.clickMapHandler)
            if (row) {
              this.map && this.map.remove(this.markers)
              this.markers = [
                {
                  name: row.wayPointName,
                  lat: row.wayPointLatitude,
                  lng: row.wayPointLongitude
                }
              ]
              this.addMarkers()
            }
          })
          .catch((e) => {
            console.log(e)
          })
      })
    },
    addMarkers() {
      const AMap = this.AMap
      if (AMap) {
        this.markers.forEach((item, index) => {
          if (item.lat && item.lng) {
            const obj = {
              position: new AMap.LngLat(item.lng, item.lat),
              zIndex: 99
            }
            this.marker = new AMap.Marker(obj)
            this.map.add([this.marker])
            // this.markers.push(marker2, marker);
          }
        })
      }
    },
    clickMapHandler(e) {
      this.temp.wayPointLongitude = e.lnglat.getLng()
      this.temp.wayPointLatitude = e.lnglat.getLat()
      this.map && this.marker && this.map.remove(this.marker)
      this.markers = [
        {
          name: '',
          lat: e.lnglat.getLat(),
          lng: e.lnglat.getLng(),
        }
      ]
      this.addMarkers()
      this.map.setCenter([e.lnglat.getLng(), e.lnglat.getLat()]);
    },
    getList() {
      this.listLoading = true
      waypointList(this.listQuery).then((response) => {
        this.list = response.list
        this.list.forEach((v, i) => {
          if (v.createTime) {
            v.createTime = formatDate(v.createTime)
          }
        })
        this.total = response.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleRefresh() {
      (this.listQuery = {
        pageNo: 1,
        pageSize: 20,
        wayPointName: undefined,
        status: undefined
      }),
        this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        wayPointNo: '',
        wayPointName: '',
        wayPointLongitude: '',
        wayPointLatitude: '',
        flightHeight: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.init()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          waypointAdd(this.temp).then(() => {
            this.btnLoading = false
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = {
        id: row.id,
        wayPointNo: row.wayPointNo,
        wayPointName: row.wayPointName,
        wayPointLongitude: row.wayPointLongitude,
        wayPointLatitude: row.wayPointLatitude,
        flightHeight: row.flightHeight
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.init(row)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      console.log(this.temp)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          this.btnLoading = true
          waypointUpdate(tempData).then(() => {
            this.btnLoading = false
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除该航点？')
        .then(() => {
          waypointDel(row.id).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        })
        .catch(() => { })
    },
    handleStatus(row) {
      this.$confirm(`确定${row.status == 1 ? '停用' : '启用'}该航点？`)
        .then(() => {
          waypointStatus({
            status: row.status == 1 ? 0 : 1,
            id: row.id
          }).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        })
        .catch(() => { })
    }
  }
}
</script>
<style lang="scss" scoped>
#qyContainer {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 400px;
}
</style>
